package leetcode.offer;

import entity.ListNode;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 2021/11/08
 */
public class offer06 {


    /**
     * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
     * 输入：head = [1,3,2]
     * 输出：[2,3,1]
     */

    @Test
    public void test() {
        ListNode list = new ListNode(1, new ListNode(2, new ListNode(3, null)));
        for (int i : reversePrintOne(list)) {
            System.out.println(i);
        }
    }

    /**
     * 使用集合操作
     *
     * @param head
     * @return
     */
    public int[] reversePrint(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        Collections.reverse(list);
        int[] arr = new int[list.size()];
        for (int i = 0; i < list.toArray(new Integer[list.size()]).length; i++) {
            arr[i] = list.get(i);
        }
        return arr;
    }

    public int[] reversePrintOne(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        while (head != null) {
            stack.push(head.val);
            head = head.next;
        }
        int[] arr = new int[stack.size()];
        int num = stack.size();
        for (int i = 0; i < num; i++) {
            arr[i] = stack.pop();
        }
        return arr;
    }


}

